// Internal action code for project skygarden

package math;

import jason.asSemantics.*;
import jason.asSyntax.*;
import java.util.Random;

import env.GardenModel;

@SuppressWarnings("serial")
public class random_direction extends DefaultInternalAction {

	Random rnd = new Random();
    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
    	 try {
             String sAction = null;

             GardenModel model = GardenModel.get();

             NumberTerm agx = (NumberTerm) args[0];
             NumberTerm agy = (NumberTerm) args[1];

             int iagx = (int) agx.solve();
             int iagy = (int) agy.solve();
             int itox = -1;
             int itoy = -1;
             while (!model.isFree(itox, itoy)) {
                 switch (rnd.nextInt(4)) {
                 case 0:
                     itox = iagx - 1;
                     sAction = "left";
                     break;
                 case 1:
                     itox = iagx + 1;
                     sAction = "right";
                     break;
                 case 2:
                     itoy = iagy - 1;
                     sAction = "up";
                     break;
                 case 3:
                     itoy = iagy + 1;
                     sAction = "down";
                     break;
                 }
             }
             return un.unifies(args[2], new Atom(sAction));
         } catch (Throwable e) {
             e.printStackTrace();
             return false;
         }
    }
}
